package com.ifinc.common.web.controller;

import com.ifinc.common.exception.ValidException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: luotao
 * Date: 13-6-3
 * Time: 下午10:23
 * To change this template use File | Settings | File Templates.
 */
public class ResultHandler {

    public String handlerInput(HttpServletRequest req, ValidException validExcetion, Action action) {
        Map<String, Object> tipMap = validExcetion.getTipMap();
        String returnType = action.returnType();
        String returnStr = validExcetion.getReturnStr();
        if (Action.json.equals(returnType)) {
            Map map = validExcetion.getTipMap();
            return null;
        } else if (Action.redirect.equals(returnType)) {
            return "redirect:" + returnStr;
        } else if (Action.forward.equals(returnType)) {
            for (Map.Entry<String, Object> entry : tipMap.entrySet()) {
                req.setAttribute(entry.getKey(), entry.getValue());
            }
            return returnStr;
        }
        return null;
    }

    public String handlerException(HttpServletRequest req, Action action, Map reqParam, SessionMap<String, Object> sessionMap, Exception e) {
        if (e instanceof ValidException) {
            ValidException validExcetion = (ValidException) e;
            Map<String, Object> tipMap = validExcetion.getTipMap();
            String returnType = action.returnType();
            String returnStr = validExcetion.getReturnStr();
            if (Action.json.equals(returnType)) {
                Map map = validExcetion.getTipMap();
                return null;
            } else if (Action.redirect.equals(returnType)) {
                return "redirect:" + returnStr;
            } else if (Action.forward.equals(returnType)) {
                for (Map.Entry<String, Object> entry : tipMap.entrySet()) {
                    req.setAttribute(entry.getKey(), entry.getValue());
                }
                return returnStr;
            }
            return null;
        }else{
            Map<String, Object> tipMap = new HashMap<String, Object>();
            String returnType = action.returnType();
            if (Action.json.equals(returnType)) {
                return null;
            } else if (Action.redirect.equals(returnType)) {
                return "redirect:" + action.exception(reqParam, tipMap, sessionMap, e);
            } else if (Action.forward.equals(returnType)) {
                String result = action.exception(reqParam, tipMap, sessionMap, e);
                for (Map.Entry<String, Object> entry : tipMap.entrySet()) {
                    req.setAttribute(entry.getKey(), entry.getValue());
                }
                return result;
            }
            return null;
        }
    }
}



